﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonDB
{
    /// <summary>
    /// 获取数据库相应字段值
    /// </summary>
    public static class DbTool
    {
        public static int GetIntFromRow(DataRow row, string columnName, int defaultValue)
        {
            if (row[columnName] is DBNull)
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return Convert.ToInt32(row[columnName]);
                }
                catch
                {
                    return defaultValue;
                }
            }
        }

        public static long GetLongFromRow(DataRow row, string columnName, long defaultValue)
        {
            if (row[columnName] is DBNull)
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return Convert.ToInt64(row[columnName]);
                }
                catch
                {
                    return defaultValue;
                }
            }
        }
        public static double GetDoubleFromRow(DataRow row, string columnName, double defaultValue)
        {
            if (row[columnName] is DBNull)
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return Convert.ToDouble(row[columnName]);
                }
                catch
                {
                    return defaultValue;
                }
            }
        }

        public static string GetStringFromRow(DataRow row, string columnName, string defaultValue)
        {
            if (row[columnName] is DBNull)
            {
                return defaultValue;
            }
            else
            {
                return row[columnName].ToString();
            }
        }

        public static DateTime GetDateTimeFromRow(DataRow row, string columnName)
        {
            try
            {
                return Convert.ToDateTime(row[columnName]);
            }
            catch
            {
                return new DateTime(1900, 1, 1);
            }
        }

        public static object GetEnumFromRow(DataRow row, string columnName, Type enumType)
        {
            object result = Enum.Parse(enumType, row[columnName].ToString(), true);
            if (!Enum.IsDefined(enumType, result))
            {
                throw new ArgumentOutOfRangeException(columnName, result, "枚举值未定义");
            }
            return result;
        }
    }
}
